package com.adk.backend.service.impl;

import com.adk.backend.entity.LxOrderTracking;
import com.adk.backend.mapper.OrderTrackingMapper;
import com.adk.backend.service.OrderTrackingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 订单跟踪服务实现类
 */
@Slf4j
@Service
public class OrderTrackingServiceImpl extends ServiceImpl<OrderTrackingMapper, LxOrderTracking> implements OrderTrackingService {
    
    @Autowired
    private OrderTrackingMapper orderTrackingMapper;
    
    @Override
    public List<Map<String, Object>> getTrackingListByOrderId(Long orderId) {
        return orderTrackingMapper.selectOrderTrackingWithStatus(orderId);
    }
    
    @Override
    public LxOrderTracking getTrackingById(Long id) {
        return orderTrackingMapper.selectById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxOrderTracking createTracking(LxOrderTracking tracking) {
        return createTracking(tracking, false);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxOrderTracking createTracking(LxOrderTracking tracking, boolean forceAdd) {
        if (tracking.getOrderId() == null || tracking.getOrderId() == 0) {
            throw new RuntimeException("订单ID不能为空");
        }
        if (tracking.getStatusCode() == null || tracking.getStatusCode() == 0) {
            throw new RuntimeException("状态代码不能为空");
        }
        
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        
        // 设置默认值
        if (tracking.getStatusTime() == null || tracking.getStatusTime() == 0) {
            tracking.setStatusTime(currentTime);
        }
        if (tracking.getAddTime() == null) {
            tracking.setAddTime(currentTime);
        }
        if (tracking.getIsShow() == null) {
            tracking.setIsShow(1); // 默认显示
        }
        if (tracking.getIsPush() == null) {
            tracking.setIsPush(0); // 默认未推送
        }
        
        // 查询是否已存在相同orderId和statusCode的记录
        QueryWrapper<LxOrderTracking> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", tracking.getOrderId());
        wrapper.eq("status_code", tracking.getStatusCode());
        wrapper.last("limit 1");
        LxOrderTracking existing = orderTrackingMapper.selectOne(wrapper);
        
        if (forceAdd) {
            // 强制添加：插入新记录，并将其他相同状态的记录is_show设为0
            orderTrackingMapper.insert(tracking);
            Long newTrackingId = tracking.getId(); // MyBatis Plus会自动设置ID
            
            // 将其他相同状态的记录的is_show设为0
            if (newTrackingId != null) {
                QueryWrapper<LxOrderTracking> updateWrapper = new QueryWrapper<>();
                updateWrapper.eq("order_id", tracking.getOrderId());
                updateWrapper.eq("status_code", tracking.getStatusCode());
                updateWrapper.ne("id", newTrackingId);
                LxOrderTracking updateTracking = new LxOrderTracking();
                updateTracking.setIsShow(0);
                orderTrackingMapper.update(updateTracking, updateWrapper);
            }
        } else {
            // 如果存在则更新，不存在则插入
            if (existing != null) {
                // 更新现有记录
                tracking.setId(existing.getId());
                tracking.setIsShow(existing.getIsShow()); // 保持原有的is_show状态
                orderTrackingMapper.updateById(tracking);
            } else {
                // 插入新记录
                orderTrackingMapper.insert(tracking);
            }
        }
        
        return tracking;
    }
    
    @Override
    public LxOrderTracking getTrackingByOrderIdAndStatusCode(Long orderId, Integer statusCode) {
        if (orderId == null || orderId == 0 || statusCode == null || statusCode == 0) {
            return null;
        }
        
        QueryWrapper<LxOrderTracking> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("status_code", statusCode);
        wrapper.last("limit 1");
        return orderTrackingMapper.selectOne(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTracking(LxOrderTracking tracking) {
        return orderTrackingMapper.updateById(tracking) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTracking(Long id) {
        return orderTrackingMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreateTracking(List<LxOrderTracking> trackingList) {
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        for (LxOrderTracking tracking : trackingList) {
            if (tracking.getAddTime() == null) {
                tracking.setAddTime(currentTime);
            }
            if (tracking.getStatusTime() == null) {
                tracking.setStatusTime(currentTime);
            }
            if (tracking.getIsShow() == null) {
                tracking.setIsShow(1);
            }
            if (tracking.getIsPush() == null) {
                tracking.setIsPush(0);
            }
            orderTrackingMapper.insert(tracking);
        }
        return true;
    }
}

